const incID = require("../functions/incID");
const Stores = require("../models/Stores")

const addStore = async (req, res) => {
    try {
        const storeExist = await Stores.findOne({ name: req.body.name });
        if (storeExist) {
            return res.status(400).json({ error_msg: '店铺已注册' });
        }
        req.body.id_store = await incID("store");
        const Storesadd = await Stores(req.body).save()

        return res.status(200).json({ success: Storesadd });

    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

const removeStore = async (req, res) => {
    try {
        const storeExist = await Stores.findById(req.body._id);
        if (storeExist) {
            const dramaremoved = await storeExist.remove()
            return res.status(200).json({ success: dramaremoved });
        }
        else {
            return res.status(400).json({ error_msg: "店铺不存在" });
        }

    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

const updateStore = async (req, res) => {
    try {
        const storeExist = await Stores.findById(req.body._id);
        if (storeExist) {
            const savequery = req.body
            delete savequery._id
            for (item in savequery) {
                console.log(typeof (savequery[item]))
                if (typeof (savequery[item]) == "object") {
                    storeExist[item] = { ...storeExist[item], ...savequery[item] }
                } else {
                    storeExist[item] = savequery[item]
                }
            }
            console.log(storeExist)
            const dramaupdated = await storeExist.save()
            return res.status(200).json({ success: dramaupdated });
        }
        else {
            return res.status(400).json({ error_msg: "店铺不存在" });
        }
    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

const getStore = async (req, res) => {
    try {
        const foundquery = req.query
        for(item in foundquery){
            foundquery[item]=eval("/"+foundquery[item]+"/")
        }
        console.log(foundquery)
        const storefound = await Stores.find(foundquery)
        if (!storefound) {
            return res.status(200).json({ error_msg: "未找到账号信息" });
        }
        return res.status(200).json({ success: storefound });
    }
    catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}


module.exports = { addStore, removeStore, updateStore,getStore }